package middleware

import (
	"context"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	pkg "sunliang.cc/package"
)

func Trace() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 全局链路标识，不存在则创建
		traceId := ctx.Request.URL.Query().Get("trace_id")
		if traceId == "" {
			traceId = uuid.NewV4().String()
		}
		pkg.Logger.WithFields(map[string]interface{}{
			"path":     reqURI(ctx.Request.RequestURI),
			"ip":       ctx.ClientIP(),
			"method":   ctx.Request.Method,
			"form":     form(ctx.Request.Form),
			"ua":       ctx.Request.UserAgent(),
			"trace_id": traceId,
		}).Info()

		// 链路标识写入后面请求
		valueCtx := context.WithValue(
			ctx.Request.Context(), "trace_id", traceId,
		)

		ctx.Set("ctx", valueCtx)
		ctx.Next()
	}
}
